package com.jjc.android.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.View
import android.widget.CheckBox
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.allen.library.SuperButton
import com.hjq.toast.ToastUtils
import com.jjc.android.*
import com.jjc.android.base.BaseActivity
import com.jjc.android.dialog.MessageImageDialog
import com.jjc.android.entity.LzyResponse
import com.jjc.android.entity.UserInfo
import com.jjc.android.net.SimpleHttpCallback
import com.jjc.android.util.*
import com.jjc.android.view.CommonKt
import com.jjc.android.view.CountDownTextView
import com.jjc.android.view.onClick
import com.jjc.android.view.textChange
import com.lzy.okgo.OkGo
import com.xw.repo.XEditText
import kotlin.properties.Delegates

class LoginActivity : BaseActivity() {

    companion object{
        fun start(context: Context){
            val intent = Intent(context,LoginActivity::class.java)
            context.startActivity(intent)
        }
    }

    override val layoutId: Int = R.layout.activity_login
    private val versionNameTxt: TextView by lazy { findViewById<TextView>(R.id.versionNameTxt) }
    private val forgetPwdBtn: SuperButton by lazy { findViewById<SuperButton>(R.id.forgetPwdBtn) }
    private val loginBtn: SuperButton by lazy { findViewById<SuperButton>(R.id.loginBtn) }
    private val agreementCheckBox: CheckBox by lazy { findViewById<CheckBox>(R.id.agreementCheckBox) }
    private val passwordInputView: LinearLayout by lazy { findViewById<LinearLayout>(R.id.passwordInputView) }
    private val passwordEt: XEditText by lazy { findViewById<XEditText>(R.id.passwordEt) }
    private val smsCodeInputView: LinearLayout by lazy { findViewById<LinearLayout>(R.id.smsCodeInputView) }
    private val sendOtpBtn: CountDownTextView by lazy { findViewById<CountDownTextView>(R.id.sendOtpBtn) }
    private val smsCodeEt: XEditText by lazy { findViewById<XEditText>(R.id.smsCodeEt) }
    private val phoneEt: XEditText by lazy { findViewById<XEditText>(R.id.phoneEt) }
    private val emailTab: FrameLayout by lazy { findViewById<FrameLayout>(R.id.emailTab) }
    private val phoneTab: FrameLayout by lazy { findViewById<FrameLayout>(R.id.phoneTab) }
    private val registerBtn: TextView by lazy { findViewById<TextView>(R.id.registerBtn) }

//    private val textChangeAction:(text: String)->Unit = {
//        loginBtn.isEnabled = CommonKt.isPhoneValid(phoneEt.text.toString())&&if(!loginBySms){
//            CommonKt.isPasswordValid(passwordEt.text.toString())
//        }else{
//            CommonKt.isSmsCodeValid(smsCodeEt.text.toString())
//        }&&agreementCheckBox.isChecked
//    }
    private var loginBySms:Boolean by Delegates.observable(true){ property, oldValue, newValue ->
        if(newValue){
            smsCodeInputView.visibility = View.VISIBLE
            passwordInputView.visibility = View.GONE
            forgetPwdBtn.visibility = View.GONE
        }else{
            smsCodeInputView.visibility = View.GONE
            passwordInputView.visibility = View.VISIBLE
            forgetPwdBtn.visibility = View.VISIBLE
        }
        phoneTab.isActivated = newValue
        emailTab.isActivated = !newValue
//        textChangeAction.invoke("")
    }

    override fun initView(savedInstanceState: Bundle?) {
        loginBySms = true
        UIStatusBarHelper.setViewForStatusBarMargin(registerBtn)
        sendOtpBtn.isEnabled = true
        agreementCheckBox.movementMethod = LinkMovementMethod()
        agreementCheckBox.text = ComplexSpannableStringUtils.getBuilder(getString(R.string.readed_agreed_txt))
            .append(getString(R.string.ag_hint_2_txt))
            .setForegroundColor(ContextCompat.getColor(this, R.color.c_831cb5))
            .setClickSpan(NoRefCopySpan {
                BrowserActivity.start(this, pageData = GlobalManager.getUserAgreementContent(), title = getString(R.string.user_ag_txt))
            })
            .append(getString(R.string.and_txt))
            .setForegroundColor(ContextCompat.getColor(this, R.color.colorPrimary))
            .append(getString(R.string.ag_hint_3_txt))
            .setForegroundColor(ContextCompat.getColor(this, R.color.c_831cb5))
            .setClickSpan(NoRefCopySpan {
                BrowserActivity.start(this, pageData = GlobalManager.getPrivacyPolicyContent(), title = getString(R.string.privacy_ag_txt))
            })
            .create()
        emailTab.setOnClickListener {
            loginBySms = false
        }
        phoneTab.setOnClickListener {
            loginBySms = true
        }
        forgetPwdBtn.onClick {
            startActivity(Intent(this,ForgetPasswordActivity::class.java))
        }
        registerBtn.onClick {
            RegisterActivity.start(this)
        }
        loginBtn.onClick {
            if(phoneEt.text.toString().isNullOrEmpty()){
                ToastUtils.show(getString(R.string.input_phone_txt))
                return@onClick
            }
            if(!CommonKt.isPhoneValid(phoneEt.text.toString())){
                ToastUtils.show(getString(R.string.input_right_phone_txt))
                return@onClick
            }
            if(loginBySms){
                if(smsCodeEt.text.isNullOrEmpty()){
                    ToastUtils.show(getString(R.string.input_sms_code_txt))
                    return@onClick
                }
                if(!CommonKt.isSmsCodeValid(smsCodeEt.text.toString())){
                    ToastUtils.show(getString(R.string.input_right_sms_code_txt))
                    return@onClick
                }
            }else{
                if(passwordEt.text.toString().isNullOrEmpty()){
                    ToastUtils.show(getString(R.string.input_pwd_txt))
                    return@onClick
                }
                if(!CommonKt.isPasswordValid(passwordEt.text.toString())){
                    ToastUtils.show(getString(R.string.re_input_right_pwd_txt))
                    return@onClick
                }
            }
            if(!agreementCheckBox.isChecked){
                ToastUtils.show(getString(R.string.read_agree_ag_txt))
                return@onClick
            }
            val params:MutableMap<String,Any?>
            val url:String
            if(loginBySms){
                params = mutableMapOf("phonenumber" to phoneEt.textEx,"smsCode" to smsCodeEt.textEx)
                url = Constants.smsLoginApp
            }else{
                params = mutableMapOf("username" to phoneEt.textEx,"password" to passwordEt.textEx)
                url = Constants.loginApp
            }
            OkGo.post<LzyResponse<UserInfo>>(url)
                .paramEx(params)
                .tag(this@LoginActivity)
                .execute(object : SimpleHttpCallback<LzyResponse<UserInfo>>(activity = this, isToastError = false){
                    override fun onCallSuccess(response: LzyResponse<UserInfo>) {
                        UserManager.loginSuccess(response.data.apply {
                            mobile = phoneEt.textEx
                        })
                        GlobalActivityStack.startAndFinishOthers(Intent(this@LoginActivity,MainActivity::class.java))
                    }

                    override fun onCallError(errorInfo: LzyResponse<*>) {
                        val error = errorInfo.msg
                        if(!error.isNullOrEmpty()){
                            if(errorInfo.code == 201){
                                MessageImageDialog.Builder(this@LoginActivity)
                                    .imageResId(R.mipmap.alert_shibai_pic)
                                    .title("提示")
                                    .content(error)
                                    .cancleText(null)
                                    .okText(if(errorInfo.code == 201) getString(R.string.to_reg_txt) else getString(R.string.reinput_txt))
                                    .okClick {
                                        if(errorInfo.code == 201){
                                            RegisterActivity.start(this@LoginActivity,phoneEt.text.toString())
                                        }else if(error.contains(getString(R.string.account_txt))||error.contains(getString(R.string.phone_txt))){
                                            phoneEt.setText("")
                                        }else{
                                            if(loginBySms){
                                                if(error.contains(getString(R.string.sms_code_txt))) {
                                                    smsCodeEt.setText("")
                                                }
                                            }else{
                                                if(error.contains(getString(R.string.password_txt))) {
                                                    passwordEt.setText("")
                                                }
                                            }
                                        }

                                    }
                                    .build()
                                    .show()
                            }else{
                                ToastUtils.show(error)
                            }
                        }
                    }

                })
        }
        sendOtpBtn.onClick {
            if(phoneEt.text.toString().isNullOrEmpty()){
                ToastUtils.show(getString(R.string.input_phone_txt))
                return@onClick
            }
            if(!CommonKt.isPhoneValid(phoneEt.text.toString())){
                ToastUtils.show(getString(R.string.input_right_phone_txt))
                return@onClick
            }
            OkGo.get<LzyResponse<String>>(Constants.captchaSmsApp)
                .params(mapOf("phonenumber" to phoneEt.textEx))
                .tag(this)
                .execute(object : SimpleHttpCallback<LzyResponse<String>>(activity = this){
                    override fun onCallSuccess(response: LzyResponse<String>) {
                        sendOtpBtn.startCountDown()
                    }

                })
        }
        versionNameTxt.text = String.format("Va%d", BuildConfig.VERSION_CODE)
    }


}